const NacosNamingClient = require("nacos").NacosNamingClient;
const { config } = require("./config");
const logger = console;
const serviceName = config.service.name;

const os = require('os');

/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
  var ifaces=os.networkInterfaces()

  for (var dev in ifaces) {
    let iface = ifaces[dev];
    for (let i = 0; i < iface.length; i++) {
      let {family, address, internal} = iface[i];
      if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
        // console.log('=======================获取本地ip：'+address)
        return address;
      }
    }
  }
}


function nacos() {
    const client = new NacosNamingClient({
        logger,
        serverList: process.env.NACOS_ADDR||config.server.list, // replace to real nacos serverList
        namespace: process.env.NACOS_SPACE||config.server.namespace,
        username: config.server.username,
        password: config.server.password
    });
    console.log(process.env.NACOS_SPACE||config.server.namespace);
    return client;
}

async function register() {
    let ip = getIpAddress();
    // spring.cloud.nacos.username=${NACOS_USER:nacos}
    // spring.cloud.nacos.password=${NACOS_PASS:Nacos@17}
    //从环境变量获取
    const client = nacos();
    await client.ready();
    client.registerInstance(
        serviceName,
        {
            // ip: config.service.ip,
            ip: ip,
            port: config.service.port
        },
        process.env.NACOS_GROUP||config.server.group
    );
}

async function discovery() {
    const client = nacos();
    await client.ready();
    const instances = await client.getAllInstances(
        serviceName,
        process.env.NACOS_GROUP||config.server.group
    );

    const [instance] = instances.filter(item => {
        return item.healthy;
    });
    const { ip, port } = instance;
    console.log(ip, port);
}

module.exports = { register, discovery };
